package ar.com.ford.it.fullEconomics.interfaces.strategys;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.interfaces.interfaz.InterfaceProccesFile;
import ar.com.ford.it.fullEconomics.logic.PartLogic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx03Intflog;
import ar.com.ford.it.fullEconomics.struct.CounterStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import cobolConversion.EbcdicString;
import cobolConversion.EbcdicTable;

public class PartStrategy implements InterfaceProccesFile {

	public String getHeaderDescription(Object aLine) {
		byte[] myBufferRead = (byte[]) aLine;
		EbcdicTable ebcdicTable = new EbcdicTable();
		String msg = null;
		String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
				.toString();
		msg = "Id de archivo :" + line.toString().substring(12, 41)
				+ "Fecha de descarga " + line.substring(50, 52) + "/"
				+ line.substring(48, 50) + "/" + line.substring(44, 48);
		return msg;
	}

	public String getTrailerDescription(Object aLine) {
		byte[] myBufferRead = (byte[]) aLine;
		EbcdicTable ebcdicTable = new EbcdicTable();
		String msg = null;
		String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
				.toString();
		String file = line.toString().substring(32, 44);
		String recCount = Integer.valueOf(line.toString().substring(56, 65)).toString();
		msg = " Nombre de archivo: " + file + " Fecha de Creacion: "
				+ line.substring(50, 52) + "/" + line.substring(48, 50) + "/"
				+ line.substring(44, 48) + "Cantidad de registros :" +recCount
				+ "   ";

		return msg;
	}
    
    public Integer getRecordCount(Object aLine) {
        byte[] myBufferRead = (byte[]) aLine;
        EbcdicTable ebcdicTable = new EbcdicTable();
        String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
                .toString();
        Integer recCount = Integer.valueOf(line.toString().substring(56, 65));
        return recCount;
    }
        
	public void processLine(Object aLine, String userId, Collection data)
			throws FullEconomicsException {
		byte[] myBufferRead = (byte[]) aLine;
		Teesp01Part part = null;
		EbcdicTable ebcdicTable = new EbcdicTable();
		
		String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
		.toString();
		
		System.out.println(line); // LSPARACI
		
		//***** TEST LSPARACI *****
		  		
		String strEesp01PartPrefixCodeC = new EbcdicString(ebcdicTable, myBufferRead, 13, 7).toString().toString().trim();
    	String strEesp01PartBaseCodeC = new EbcdicString(ebcdicTable, myBufferRead, 19, 9).toString().toString().trim();
		String strEesp01PartSuffixCodeC = new EbcdicString(ebcdicTable, myBufferRead, 27, 9).toString().toString().trim();
		String strEesp01PartDescriptionX = new EbcdicString(ebcdicTable, myBufferRead, 35, 35).toString().toString().trim();
		String strEesp01PartUnitmeasureCodeC = new EbcdicString(ebcdicTable, myBufferRead, 185, 4).toString().toString().trim();
		String strEesp01PartCommodLowCodeC = new EbcdicString(ebcdicTable, myBufferRead, 443, 5).toString().toString().trim();
		
		String strAnio = new EbcdicString(ebcdicTable, myBufferRead, 206, 5).toString().toString().trim();
		String strMes = new EbcdicString(ebcdicTable, myBufferRead, 210, 3).toString().toString().trim();
		String strDia = new EbcdicString(ebcdicTable, myBufferRead, 212, 3).toString().toString().trim();
		
		String strEesp01PartInDateY = strDia + "/" + strMes + "/" + strAnio;
		
		if (strEesp01PartInDateY.equalsIgnoreCase("00/00/0000")) 
			strEesp01PartInDateY ="01/01/1900";
		
		
		Collection<Teesg01Plant> plantasaux = new ArrayList<Teesg01Plant>();
		
		// Plantas donde se insertara la parte
		int iPosicion = 225;//219;
		for (int countPlant = 0; countPlant < 10; countPlant++) {
			String codePlantAlter = new EbcdicString(ebcdicTable, myBufferRead, iPosicion, 3).toString().toString().trim();
			 iPosicion = iPosicion + 6;
			if (!codePlantAlter.equals("")
					&& codePlantAlter.matches("[0-9A-Za-z]+")) {
                Teesg01Plant plant = new Teesg01Plant();
                plant.setEesg01PlantAlternateCodeC(codePlantAlter);
				plantasaux.add(plant);
			}
		} 
		
		String snuevo = ">>> BIN: F-" + strEesp01PartPrefixCodeC + "-" +
				strEesp01PartBaseCodeC + "-" +
				strEesp01PartSuffixCodeC + "-" +
				strEesp01PartDescriptionX + "-" +
				strEesp01PartUnitmeasureCodeC + "-" +
				strEesp01PartCommodLowCodeC + "-" +
				strEesp01PartInDateY + "-";
		
		for (Iterator iterPlantasaux = plantasaux.iterator(); iterPlantasaux.hasNext();) {
	        
        	Teesg01Plant plant = (Teesg01Plant) iterPlantasaux.next();
        	snuevo = snuevo + plant.getEesg01PlantCodeC() + "[" + plant.getEesg01PlantAlternateCodeC() + "]";
		}
		
		System.out.println(snuevo);
		  
        // ***** END TEST LSPARACI *****
		
		
		if (line.toString().substring(12, 13).equals("1")) {
			Collection<Teesg01Plant> plantas = new ArrayList<Teesg01Plant>();
			part = new Teesp01Part();
			
			//----- LSPARACI
			part.setEesp01PartClassCodeC("F");
			part.setEesp01PartPrefixCodeC(strEesp01PartPrefixCodeC);
			part.setEesp01PartBaseCodeC(strEesp01PartBaseCodeC);
			part.setEesp01PartSuffixCodeC(strEesp01PartSuffixCodeC);
			part.setEesp01PartDescriptionX(strEesp01PartDescriptionX);
			part.setEesp01PartUnitmeasureCodeC(strEesp01PartUnitmeasureCodeC);
			part.setEesp01PartCommodLowCodeC(strEesp01PartCommodLowCodeC);
			
			Timestamp inDate = new Timestamp(FullEconomicsDateUtil
					.format(strEesp01PartInDateY).getTimeInMillis());
            			
			part.setEesp01PartInDateY(inDate);
			part.setEesp01PartOutDateY(FullEconomicsDateUtil.maxDate());
			
			System.out.println(part.toString());
		
			
			/*
			
			// Pieza
			part.setEesp01PartPrefixCodeC(line.substring(13, 19).trim());
			part.setEesp01PartBaseCodeC(line.substring(19, 27).trim());
			part.setEesp01PartSuffixCodeC(line.substring(27, 35).trim());
			// Descripcion
			part.setEesp01PartDescriptionX(line.substring(35, 69).trim());
			// Unidad de medida
			part.setEesp01PartUnitmeasureCodeC(line.substring(185, 188).trim());
			// Clase de parte
			part.setEesp01PartClassCodeC("F");
			// Comodity si lo posee
			part.setEesp01PartCommodLowCodeC(line.substring(443, 447));
			// Fecha de in
			String anio = line.toString().substring(206, 210);
			String mes = line.toString().substring(210, 212);
			String dia = line.toString().substring(212, 214);
			part.setEesp01PartInDateY(new Timestamp(FullEconomicsDateUtil
					.format(dia + "/" + mes + "/" + anio).getTimeInMillis()));
			part.setEesp01PartOutDateY(FullEconomicsDateUtil.maxDate());
			// Plantas donde se insertara la parte
			int iPos = 219;
			int fPos = 221;
			for (int countPlant = 0; countPlant < 10; countPlant++) {
				String codePlantAlter = line.substring(iPos = iPos + 6,
						fPos = fPos + 6);
				if (!codePlantAlter.equals("")
						&& codePlantAlter.matches("[0-9A-Za-z]+")) {
                    Teesg01Plant plant = new Teesg01Plant();
                    plant.setEesg01PlantAlternateCodeC(codePlantAlter);
					plantas.add(plant);
				}
			}
			
			String strFollow = "Part: ";
			strFollow = strFollow + part.getEesp01PartClassCodeC();
			strFollow = strFollow + "-" + part.getEesp01PartPrefixCodeC();
			strFollow = strFollow + "-" + part.getEesp01PartBaseCodeC();
			strFollow = strFollow + "-" + part.getEesp01PartSuffixCodeC();
			strFollow = strFollow + "-->" + part.getEesp01PartDescriptionX();
			strFollow = strFollow + "-" + part.getEesp01PartUnitmeasureCodeC();
			strFollow = strFollow + "-" + part.getEesp01PartCommodLowCodeC();
			strFollow = strFollow + "-- In:" + part.getEesp01PartInDateY();
			strFollow = strFollow + "Out:" + part.getEesp01PartOutDateY()+ "-- Plantas:" ;
			
			for (Iterator iterPlants = plantas.iterator(); iterPlants.hasNext();) {
		        
            	Teesg01Plant plant = (Teesg01Plant) iterPlants.next();
			    strFollow = strFollow + plant.getEesg01PlantCodeC() + "[" + plant.getEesg01PlantAlternateCodeC() + "]";
			}
			
			System.out.println(strFollow);			
			
			*/
            for(Teesg01Plant plant : plantasaux){
                Teesp01Part partInPlant = new Teesp01Part(part);
                partInPlant.setEesp01PlantCodeC(plant);
                data.add(partInPlant);
            }
		}   
	}
    public CounterStruct insertData(Collection data, String userId, Teesx03Intflog logNumber) throws FullEconomicsException{
        PartLogic logic = new PartLogic();
        Collection<Teesp01Part> parts= (Collection<Teesp01Part>) data;
        CounterStruct counter = logic.createOrUpdateWIPS(parts, userId, logNumber);
        return counter;
    }

	/**
	 * Valida si la linea leida corresponde a header o al trailer
	 */
	public boolean validateHeaderAndTrailer(Object line) {
		byte[] myBufferRead = (byte[]) line;
		EbcdicTable ebcdicTable = new EbcdicTable();
		ebcdicTable.set_pageCode(EbcdicTable.ASCII_USA_00437);
		EbcdicString ebcdicString = new EbcdicString(ebcdicTable, myBufferRead);
		
		String sLine = ebcdicString.toString().toString().trim();
		System.out.println("EvalHeadTrail -->>" + sLine);
		//System.out.println(sLine.substring(4, 30));
		
		String sTrailerMatch = new EbcdicString(ebcdicTable, myBufferRead, 12, 29).toString().toString().trim();
		String sHeaderMatch = new EbcdicString(ebcdicTable, myBufferRead, 4, 27).toString().toString().trim();
		
		//sLine.substring(12,40).equalsIgnoreCase("ARGENTINA TRAILER - DB2 PART"
		//sLine.substring(4, 30).equalsIgnoreCase("00000001WIPS FOR ARGENTINA")
		
		if (sTrailerMatch.equalsIgnoreCase("ARGENTINA TRAILER - DB2 PART")
				|| sHeaderMatch.equalsIgnoreCase("00000001WIPS FOR ARGENTINA")) {
			return false;
		} else {
			return true;
		}
	}

    public boolean validateRecordCount(int trailerRecordCount, int lineCount, int dataSize) {
        if(trailerRecordCount == lineCount -2)
            return true;
        return false;
    }
    


}
